﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

using ZhimeiSoft.Framework.Client.Context;
using ZhimeiSoft.Framework.Common.Enums;
using ZhimeiSoft.Framework.Common.RefectUtils;
using ZhimeiSoft.CharmManager.Interface;


namespace ZhimeiSoft.CharmManager.Client.Manager
{
    public class BussinessProxyManager
    {
        private static IBusinessService service;

        public static IBusinessService Instance
        {

            get 
            {
                if (service == null)
                {
                    string accessMode = ClientContext.Properties["ACCESSMODE"];
                    string serviceUrl = ClientContext.Properties["SERVICEURL"];
                    AccessModeEnum accessModeEnum = (AccessModeEnum)Convert.ToInt32(accessMode);
                    CreateBusinessProxy(accessModeEnum, serviceUrl);
                }
                return service;
            }

            
            set { service = value; }
        }

        public static bool HasInstance
        {
            get { return service != null; }
        }

        /// <summary>
        /// 创建CharmManager服务
        /// </summary>
        /// <param name="accessMode">访问方式</param>
        /// <param name="serviceUrl">服务Web Serive地址</param>
        public static void CreateBusinessProxy(AccessModeEnum accessMode, string serviceUrl)
        {
            Assembly assembly = typeof(IBusinessService).Assembly;
            try
            {
                switch (accessMode)
                {
                    case AccessModeEnum.emWebService:
                        service = (IBusinessService)ReflectHelper.Instance.CreateObject(assembly,
                            @"ZhimeiSoft.CharmManager.Client.Proxy.WebService",
                            @"ZhimeiSoft.CharmManager.Client.Proxy.WebService.WebServiceBusinessProxy",
                            new object[] { serviceUrl }
                            );
                        break;
                    case AccessModeEnum.emLocal:
                        service = (IBusinessService)ReflectHelper.Instance.CreateObject(assembly,
                            @"ZhimeiSoft.CharmManager.Client.Proxy.Local",
                            @"ZhimeiSoft.CharmManager.Client.Proxy.Local.LocalBusinessProxy",
                            new object[] { }
                            );
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("连接服务出错", ex);
            }
        }
    }
}
